#include "texteditor.h"

TextEditor::TextEditor(QString filename, QWidget *parent) :
    QPlainTextEdit(parent)
{
    this->setFrameShape(QFrame::NoFrame);
    this->setAttribute(Qt::WA_DeleteOnClose);
    this->setTabStopWidth(20);
    this->setFont(QFont("Monospace", 10));

    filename_ = filename.right(filename.length() - filename.lastIndexOf("/") - 1);
    filePath_ = filename.left(filename.lastIndexOf("/") + 1);

    highlighter_ = new HtmlSyntaxHighlighter(this);
    highlighter_->setDocument(this->document());
}

void TextEditor::saveFile()
{
    QString filename;

    if(filePath_.isEmpty()) {
        filename = QFileDialog::getSaveFileName(this, "Save file", QString(),
                       "HTML files (*.html *.htm);;Text files (*.txt)");

        if(filename.isEmpty())
            return;
        else {
            filename_ = filename.right(filename.length() - filename.lastIndexOf("/") - 1);
            filePath_ = filename.left(filename.lastIndexOf("/") + 1);
        }
    }

    filename = filePath_ + filename_;

    QFile file(filename);
    if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return;

    file.write(this->toPlainText().toAscii());
    file.close();

    emit saved();
}
